package com.hlx.util;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES对称加密工具类
 */
public class AESUtil {
    /**
     * 偏移量
     * 此处值与前端偏移量值保持一致
     */
    private static String IV = "37fa77f6a3b0462d";

    /**
     * 唯一key作为密钥
     * 此处值与前端偏移量值保持一致
     */
    public static String KEY = "385f33cb91484b04a177828829081ab7";


    /**
     * 加密
     *
     * @param src       加密内容
     * @param uniqueKey 加密key
     */
    public static String encrypt(String src, String uniqueKey) throws Exception {
        byte[] key = uniqueKey.getBytes();
        SecretKey secretKey = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("utf-8"));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] cipherBytes = cipher.doFinal(src.getBytes("UTF-8"));
        return byteToHexString(cipherBytes);
    }

    /**
     * 解密
     *
     * @param enc       加密内容
     * @param uniqueKey 唯一key
     */
    public static String decrypt(String enc, String uniqueKey) throws Exception {
        byte[] key = uniqueKey.getBytes();
        SecretKey secretKey = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes("utf-8"));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] hexBytes = hexStringToBytes(enc);
        byte[] plainBytes = cipher.doFinal(hexBytes);
        return new String(plainBytes, "UTF-8");
    }

    /**
     * 将byte数组转换为16进制字符串
     *
     * @param src
     * @return
     */
    private static String byteToHexString(byte[] src) {
        return Hex.encodeHexString(src);
    }

    /**
     * 将16进制字符串转换为byte数组
     *
     * @param hexString
     * @return
     */
    private static byte[] hexStringToBytes(String hexString) throws DecoderException {
        return Hex.decodeHex(hexString);
    }

    /**
     * AES加密、解密测试方法
     */
    public static void main(String[] args) throws Exception {
        String src = "D:/00-Project/01-VMware";
        System.out.println("原字符串:" + src);

        // 加密
        String encrypt = encrypt(src, KEY);
        System.out.println("加密：" + encrypt);

        // 解密
        String decrypt = decrypt(encrypt, KEY);
        System.out.println("解密：" + decrypt);
    }
}